package cn.oms.oms.service.impl;

import cn.oms.oms.entity.Department;
import cn.oms.oms.entity.Druginfo;
import cn.oms.oms.entity.Item;
import cn.oms.oms.exception.ServiceException;
import cn.oms.oms.mapper.DepartmentMapper;
import cn.oms.oms.mapper.DruginfoMapper;
import cn.oms.oms.mapper.ItemMapper;
import cn.oms.oms.service.IDruginfoService;
import cn.oms.oms.vo.DrugInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AllenChen曾晨
 * @since 2022-04-29
 */
@Service
public class DruginfoServiceImpl extends ServiceImpl<DruginfoMapper, Druginfo> implements IDruginfoService {

    @Autowired
    private DruginfoMapper druginfoMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 根据查询条件查询库存列表
     * @param drugInfoVo
     * @return
     */
    @Override
    public PageInfo<Druginfo> selectDrugInfoList(DrugInfoVo drugInfoVo) {
        QueryWrapper<Druginfo> query = new QueryWrapper<>();
        if (drugInfoVo.getDepartmentId()!=null&& !"".equals(drugInfoVo.getDepartmentId())){
            query.eq("departmentId",drugInfoVo.getDepartmentId());
        }
        if (StringUtil.isNotEmpty(drugInfoVo.getItemDescription())){
            QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("itemName",drugInfoVo.getItemDescription())
                    .or().like("itemNameSN",drugInfoVo.getItemDescription())
                    .or().like("ingredientName",drugInfoVo.getItemDescription());
            queryWrapper.eq("deleteFlag",0);
            List<Item> items = itemMapper.selectList(queryWrapper);
            List<Integer> itemIdList = new ArrayList<>();
            if (items.size()>0&&items!=null){
                for (Item item:items){
                    itemIdList.add(item.getItemId());
                }
            }
            if (itemIdList.size()>0&&itemIdList!=null){
                query.in("itemId",itemIdList);
            }
        }
        query.eq("deleteFlag",0);
        PageHelper.startPage(drugInfoVo.getPageNum(),drugInfoVo.getPageSize());
        List<Druginfo> druginfos = druginfoMapper.selectList(query);

        for (Druginfo druginfo:druginfos){
            // 插入科室名称
            QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",druginfo.getDepartmentId());
            queryWrapper.eq("deleteFlag",0);
            Department department = departmentMapper.selectOne(queryWrapper);
            if (department!=null){
                druginfo.setDepartmentIdName(department.getDepartmentName());
            }
            // 日期格式化
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(druginfo.getCreateTime());
            druginfo.setReturnCreateTime(format);
        }
        return new PageInfo<>(druginfos);
    }

    /**
     * 查询详情
     * @param drugInfoVo
     * @return
     */
    @Override
    public Druginfo selectDrugInfoDetail(DrugInfoVo drugInfoVo) {
        if (drugInfoVo.getStockId()==null||"".equals(drugInfoVo.getStockId())){
            throw new ServiceException("参数异常，药库Id为空");
        }

        QueryWrapper<Druginfo> query = new QueryWrapper<>();

        if (drugInfoVo.getItemId()!=null&&!"".equals(drugInfoVo.getItemId())){
            query.eq("itemId",drugInfoVo.getItemId());
        }

        query.eq("stockId",drugInfoVo.getStockId());
        query.eq("deleteFlag",0);
        Druginfo druginfo = druginfoMapper.selectOne(query);
        if (druginfo==null){
            throw new ServiceException("参数异常，未找到库存记录");
        }

        // 插入科室名称
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",druginfo.getDepartmentId());
        queryWrapper.eq("deleteFlag",0);
        Department department = departmentMapper.selectOne(queryWrapper);
        if (department!=null){
            druginfo.setDepartmentIdName(department.getDepartmentName());
        }
        // 日期格式化
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(druginfo.getCreateTime());
        druginfo.setReturnCreateTime(format);


        return druginfo;
    }

    /**
     * 新增库存
     * @param drugInfoVo
     * @return
     */
    @Override
    public String addDrugInfo(DrugInfoVo drugInfoVo) {

        Druginfo druginfo = new Druginfo();
        if(drugInfoVo.getDepartmentId()==null||"".equals(drugInfoVo.getDepartmentId())){
            throw new ServiceException("参数异常，药房ID不能为空");
        }
        druginfo.setDepartmentId(drugInfoVo.getDepartmentId());

        if(drugInfoVo.getItemId()==null||"".equals(drugInfoVo.getItemId())){
            throw new ServiceException("参数异常，产品ID不能为空");
        }

        QueryWrapper<Item> query = new QueryWrapper<>();
        query.eq("itemId",drugInfoVo.getItemId());
        query.eq("deleteFlag",0);
        Item item = itemMapper.selectOne(query);
        if (item==null){
            throw new ServiceException("参数异常，未找到产品");
        }

        // 判断药库中这个药房是否已经有了这个药
        QueryWrapper<Druginfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("departmentId",drugInfoVo.getDepartmentId());
        queryWrapper.eq("itemId",drugInfoVo.getItemId());
        List<Druginfo> druginfos = druginfoMapper.selectList(queryWrapper);
        if (druginfos.size()>0&&druginfos!=null){
            throw new ServiceException("当前药品已存在该药房");
        }

        druginfo.setItemId(item.getItemId());
        druginfo.setItemDescription(item.getItemName()+"("+item.getItemNameSN() + ")" + item.getItemSpecificationDetail() + " " + item.getManufacturerName() + " " + item.getManufacturerApprovalId());

        if (StringUtil.isNotEmpty(drugInfoVo.getUnitName())){
            druginfo.setUnitName(drugInfoVo.getUnitName());
        }

        if (drugInfoVo.getTotalQty()!=null&&!"".equals(drugInfoVo.getTotalQty())){
            druginfo.setTotalQty(drugInfoVo.getTotalQty());
            druginfo.setAvailableQty(drugInfoVo.getTotalQty());
            druginfo.setFreezeQty(0);
        }

        druginfo.setCreateTime(new Date());
        druginfo.setDeleteFlag(0);

        int num = druginfoMapper.insert(druginfo);

        if (num!=1){
            throw new ServiceException("数据库新增异常！！！");
        }

        return "ok";
    }

    /**
     * 修改库存
     * @param drugInfoVo
     * @return
     */
    @Override
    public String updateDrugInfo(DrugInfoVo drugInfoVo) {

        if (drugInfoVo.getStockId()==null||"".equals(drugInfoVo.getStockId())){
            throw new ServiceException("参数异常，库存ID为空");
        }
        QueryWrapper<Druginfo> query = new QueryWrapper<>();
        query.eq("stockId",drugInfoVo.getStockId());
        query.eq("deleteFlag",0);
        Druginfo druginfo = druginfoMapper.selectOne(query);
        if (druginfo==null){
            throw new ServiceException("参数异常，库存记录不存在");
        }
        if (drugInfoVo.getAvailableQty()!=null&&!"".equals(drugInfoVo.getAvailableQty())){
            druginfo.setAvailableQty(drugInfoVo.getAvailableQty());
        }

        Integer availableQty = drugInfoVo.getAvailableQty();
        Integer freezeQty = druginfo.getFreezeQty();

        Integer totalQrt = availableQty+freezeQty;
        druginfo.setTotalQty(totalQrt);
        int num = druginfoMapper.updateById(druginfo);

        if (num!=1){
            throw new ServiceException("数据库新增异常！！！");
        }

        return "ok";
    }

    /**
     * 删除库存
     * @param id
     * @return
     */
    @Override
    public String deleteDrugInfo(Integer id) {

        if (id==null||"".equals(id)){
            throw new ServiceException("参数异常，库存ID不能为空");
        }
        QueryWrapper<Druginfo> query = new QueryWrapper<>();
        query.eq("stockId",id);
        query.eq("deleteFlag",0);

        Druginfo druginfo = druginfoMapper.selectOne(query);

        if (druginfo==null){
            throw new ServiceException("参数异常，库存记录未找到");
        }

        druginfo.setDeleteFlag(1);
        int num = druginfoMapper.updateById(druginfo);

        if (num!=1){
            throw new ServiceException("数据库新增异常！！！");
        }

        return "ok";
    }
}
